<template>
  <div class="gl_contentBox gl_heightFull">
    <p style="border-bottom:1px solid rgba(0, 0, 0, 0.1);padding:4px">{{ this.$route.query.id ? '编辑新闻' : '新建新闻' }}</p>
    <el-row>
      <el-col :span="12">
        <el-form
          v-if="!loading"
          ref="newsInputForm"
          label-width="100px"
          :rules="AddNews_Rules"
          :model="newsInput"
          size="mini"
        >
          <div style="padding: 15px">
            <el-row>
              <el-col :span="14">
                <el-form-item label="新闻类型" prop="newsTypeId">
                  <el-select v-model="newsInput.newsTypeId" size="mini" style="width:100%" @change="changeNewsType">
                    <el-option v-for="(item,index) in newsTypeList" :key="index" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
                <el-form-item label="新闻标题" prop="title">
                  <el-input v-model.trim="newsInput.title" :maxlength="30" size="small" style="width:100%" />
                </el-form-item>
                <el-form-item label="作者" prop="author">
                  <el-input v-model.trim="newsInput.author" size="small" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label-width="20px" align="center" prop="coverImage">
                  <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
                    <photo-cropper ref="photoCropper" :photograph="false" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
                  </el-dialog>
                  <div class="upload_game_img" @click="openPhotoCropper">
                    <img v-if="newsInput.coverImage" class="show_img" :src="getStaticPhotoUrl(newsInput.coverImage)">
                    <i v-else class="el-icon-plus" />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="新闻内容" prop="description">
              <div v-if="!(this.$route.query.id && !newsInput.description)">
                <Tinymce v-model="newsInput.description" :height="300" />
              </div>
            </el-form-item>
            <el-form-item label="定时发送" prop="isDelayed">
              <el-checkbox v-model="newsInput.isDelayed" />
            </el-form-item>
            <el-form-item v-if="newsInput.isDelayed" label="发送时间" prop="publishTime">
              <el-date-picker
                v-model="newsInput.publishTime"
                type="datetime"
                placeholder="选择日期时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
              />
            </el-form-item>
          </div>
          <div style="text-align:left; padding-left: 120px;">
            <span class="anniu">
              <el-button size="mini" @click="goBack">取消</el-button>
              <el-button type="primary" :loading="submitLoading" size="mini" @click="submitAddNews(false)">存草稿</el-button>
              <el-button type="default" :loading="submitLoading" size="mini" @click="openPreview">预览</el-button>
              <el-button type="success" :loading="submitLoading" :disabled="newsInput.isDelayed" size="mini" @click="submitAddNews(true)">发布</el-button>
            </span>
          </div>
        </el-form>
      </el-col>
    </el-row>
    <!-- 预览弹窗 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="420px"
      title="预览"
      :visible.sync="isPreview"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <mobilePreview :item="newsInput" />
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
// import { FormatDate } from '@/lib';
import {
  api_POST_EventsManagementNews, // 创建新闻
  api_GET_EventsManagementNewsId, // 获取指定新闻
  api_PUT_EventsManagementNewsId, // 更新新闻
  api_GET_EventsManagementNewsType // 获取新闻类型
} from '@/extend/api/gameswaggerApi/app.js';
import {
  CreateNewsInput,
  Api_GET_EventsManagementNewsTypeQO
} from '@/lib/form/game/swaggerForm';
import { AddNews_Rules } from '@/lib/validate/wxApp/index.js';
import Tinymce from '@/components/Tinymce';
import photoCropper from '@/components/PhotoCropper';
import mobilePreview from './mobilePreview.vue';
export default {
  components: {
    Tinymce,
    photoCropper,
    mobilePreview
  },
  data() {
    return {
      loading: false,
      newsTypeList: [],
      newsTypeQO: new Api_GET_EventsManagementNewsTypeQO(),
      newsInput: new CreateNewsInput(),
      AddNews_Rules: new AddNews_Rules(),
      newsId: null,
      submitLoading: false,
      // 封面上传
      photoCropperVisible: false, // 上传图片窗口的显示与隐藏
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      photoCropperOption: {
        img: '',
        autoCropWidth: '242px',
        autoCropHeight: '153px',
        enlarge: 1,
        fixedNumber: [242, 153]
      },
      // 预览
      isPreview: false
    };
  },
  computed: {
    ...mapState({
      info: state => state.user.info,
      dict: state => state.dict.dict
    })
  },
  mounted() {
    // 是否编辑模板
    if (this.$route.query.id) {
      this.newsId = this.$route.query.id;
      this.getNewsInfo();
    } else {
      this.newsInput.author = this.info && this.info.name ? this.info.name : '';
    }
    this.getDict();
    this.getNewsType();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取新闻详情
    getNewsInfo() {
      this.loading = true;
      api_GET_EventsManagementNewsId(this.newsId).then(
        res => {
          if (res) {
            this.loading = false;
            this.newsInput = res;
          }
        },
        error => {
          this.loading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 获取新闻类型
    getNewsType() {
      api_GET_EventsManagementNewsType().then(
        res => {
          this.newsTypeList = res.items || [];
        },
        error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 选择模板类型
    changeNewsType(val) {},
    // 预览
    openPreview() {
      this.isPreview = true;
    },
    // 确认新建
    submitAddNews(flag) {
      this.$refs['newsInputForm'].validate(valid => {
        if (valid) {
          if (flag) {
            this.newsInput.isPublished = true;
          }
          if (this.newsInput.isDelayed && !this.newsInput.publishTime) {
            this.$message({
              type: 'error',
              message: '请选择发送时间'
            });
          } else {
            if (this.newsInput.isDelayed) {
              this.newsInput.isPublished = true;
            }
            if (this.newsId) {
              this.updateNews();
            } else {
              this.createNews();
            }
          }
        }
      });
    },
    // 更新
    updateNews() {
      this.submitLoading = true;
      api_PUT_EventsManagementNewsId(this.newsId, this.newsInput).then(
        () => {
          this.$message({
            message: '更新成功',
            type: 'success'
          });
          this.submitLoading = false;
          this.goBack();
        },
        error => {
          this.submitLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 新建
    createNews() {
      this.submitLoading = true;
      api_POST_EventsManagementNews(this.newsInput).then(
        () => {
          this.$message({
            message: '创建成功',
            type: 'success'
          });
          this.submitLoading = false;
          this.goBack();
        },
        error => {
          this.submitLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper () {
      if (this.newsInput['coverImage']) {
        this.$set(this.photoCropperOption, 'img', this.getStaticPhotoUrl(this.newsInput['coverImage']));
      }
      this.photoCropperVisible = true;
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$set(this.newsInput, 'coverImage', res.tempUrl);
        this.photoCropperVisible = false;
      });
    },
    // 返回
    goBack() {
      this.$router.push({
        name: 'news'
      });
    },
    // 获取静态文件
    getStaticPhotoUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 获取静态文件
    getStaticUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_TEMPLATE_STATIC_FILE_RUL + relativeUrl;
    }
  }
};
</script>

<style lang="scss" scoped>
.gl_contentBox {
  box-sizing: border-box;
}

.upload_game_img.no_pointer {
  cursor: default;
}
.upload_game_img {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 153px;
  width: 242px;
  line-height: 205px;
  text-align: center;
  font-size: 20px;
  border: 1px dotted #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}
.upload_game_img .show_img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  vertical-align: middle;
}
</style>
